import React, { useState, useLayoutEffect } from 'react';
import { Upload, message, Button } from 'antd';
import { UploadOutlined, DeleteOutlined } from '@ant-design/icons';
import FileOpen from '@/components/FileIframOpen';

interface FileUploadNewProps {
    actionUrl?: string;
    listType?: 'text' | 'picture' | 'picture-card';
    type?: string;
    multiple?: boolean;
    directory?: boolean;
    readOnly?: boolean;
    ossEnum?: any;
    max?: number;
    href?: string;
    hrefText?: string;
    hrefTaget?: string;
    text?: string;
    value?: any;
    onChange?: any;
}

const FileUploadNew: React.FC<FileUploadNewProps> = (props) => {
    const {
        actionUrl,
        listType,
        type,
        multiple,
        directory,
        readOnly,
        ossEnum,
        max,
        href,
        hrefTaget,
        hrefText,
        text,
        value
    } = props
    const [fileList, setFileList] = useState<any[]>([]);
    const [showFile, setShowFile] = useState<boolean>(false);
    const [postFileList, setPostFileList] = useState<any[]>(value || []);

    // 有默认值的先赋值
    useLayoutEffect(() => {
        setPostFileList(() => {
            return value || [];
        });
        setFileList(() => {
            return value || [];
        });
        console.log(value, 'value');
    }, []);
    // 修改父组件的值
    const propPostChange = (pFs: any) => {
        const { onChange } = props;
        if (onChange) {
            console.log(pFs, 'pFs');

            onChange(pFs);
        }
    };
    // 上传前做大小判断
    const beforeUpload = (file: any) => {
        // 无法控制显示名称，在onChange中控制
        const isLt12M = file.size / 1024 / 1024 <= 500;
        if (!isLt12M) {
            // file['name'] = '文件大小不能超过 12MB!';
            file.status = 'error';
            message.error('文件大小不能超过 500MB!');
        }
        return isLt12M;
    };

    const onChange = ({ file, fileList: newFileList = [] }: any) => {
        console.log(file, newFileList, '11');
        if (!file.status) {
            return;
        }
        if (file.status == 'done') {
            const response = file.response;
            if (response && response.success) {
                setPostFileList((files) => {
                    files.push(Object.assign({ ...file, fileId: response.data.fileId }, response.data, { type: [] }));
                    return files;
                });
                propPostChange(postFileList);
            } else {
                file.status = 'error';
                file.name = response.errMsg || '上传失败';
                message.error(response.errMsg || '系统超时，请刷新重试！');
            }
        }
        setFileList([...newFileList])
    }
    const onRemove = (file: any) => {
        console.log(file, 'file');

        let index = -1,
        statuIndex = -1;
        const newFileList = fileList.concat();
        let fileId = file.fileId || file.response.data.fileId
        postFileList.map((el: any, i: number) => {
            if (el.fileId == fileId) {
                index = i;
            }
        });
        newFileList.map((el: any, i: number) => {
            if (el.fileId == fileId) {
                statuIndex = i;
                el.status = 'remove';
            }
        });
        if (index > -1) {
            setPostFileList((fs) => {
                fs.splice(index, 1);
                return fs;
            });
            propPostChange(postFileList);
        }
    }
    return <>
        <Upload
            action={actionUrl || '/api/upload/resource'}
            listType={listType || 'picture'}
            accept={type || ''}
            fileList={fileList}
            multiple={multiple || true}
            directory={directory || false}
            disabled={readOnly}
            beforeUpload={beforeUpload}
            onChange={onChange}
            onRemove={onRemove}
            data={{
                ossEnum,
            }}
            maxCount={max}
        >
            {fileList.length < (max || 5) && !readOnly && (
                <Button icon={<UploadOutlined />}>{text || '点击上传'}</Button>
            )}
        </Upload>
        {href && (
            <>
                {hrefTaget == 'open' ? (
                    <a
                        style={{ position: 'absolute', top: '5px', left: '130px' }}
                        onClick={() => {
                            setShowFile(true);
                        }}
                    >
                        {hrefText || ''}
                    </a>
                ) : (
                    <a
                        style={{ position: 'absolute', top: '5px', left: '130px' }}
                        href={href}
                        target={hrefTaget}
                        download
                    >
                        {hrefText || ''}
                    </a>
                )}
            </>
        )}
        {showFile && (
            <FileOpen
                title={hrefText || ''}
                fielUrl={href || ''}
                download={2}
                modalVisible={showFile}
                onCancel={() => {
                    setShowFile(false);
                }}
            />
        )}
    </>
}
export default FileUploadNew;